/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import pojo.Scheduledata;

/**
 *
 * @author javauser
 */
//class that handles making schedule task for Provider on linux
public class CustomSchTask extends Thread {

    Scheduledata data;
    String providername;

    public CustomSchTask(Scheduledata data, String providername) {
        try {
            this.data = data;
            this.providername = providername;
            Date scdate = data.getStartDate();
            String fullDateTime = scdate.toString() + " " + data.getStartTime();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date taskFullDate = formatter.parse(fullDateTime);

            Calendar now = Calendar.getInstance();
            //now.add(Calendar.HOUR, -1);
            String todNow = new String(now.get(Calendar.YEAR) + "-" + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DATE) + " " + now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE));
            Date nowDate = formatter.parse(todNow);
            long diff = taskFullDate.getTime() - nowDate.getTime();
            System.out.println("Task Full Date is : " + taskFullDate);
            System.out.println("Now Date is : " + nowDate);
            System.out.println("Difference date is : " + diff);
            sleep(diff);
            start();
        } catch (Exception ex) {
            Logger.getLogger(CustomSchTask.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void run() {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document config = builder.parse("/home/ahmed/NetBeansProjects/trunk/Book Dimension Project/src/java/Configuration/linconfig.xml");
            Element pathelement = (Element) config.getElementsByTagName("jar-path").item(0);
            Element jrePath = (Element) config.getElementsByTagName("jre-path").item(0);
            String min = "*";
            String hour = "*";
            String dayOfMon = "*";
            String mon = "*";
            String day = "*";
            String mod = data.getModifier();
            if (Integer.parseInt(mod) > 1) {
                String schedule = data.getSchedule();
                if (schedule.equalsIgnoreCase("hourly")) {
                    hour = "*/" + mod;
                } else if (schedule.equalsIgnoreCase("daily")) {
                    dayOfMon = "*/" + mod;
                } else if (schedule.equalsIgnoreCase("weekly")) {
                    day = "*/" + mod;
                } else if (schedule.equalsIgnoreCase("monthly")) {
                    mon = "*/" + mod;
                }
            }
            FileOutputStream fos = null;
            String taskTime = min + " " + hour + " " + dayOfMon + " " + mon + " " + day + " export DISPLAY=:0 && " + jrePath.getTextContent().trim() + "/bin/java -jar " + pathelement.getTextContent().trim() + "  " + providername + " " + "\n";
            String fileName = "/home/ahmed/Desktop/CronJobs";
            try {
                RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
                raf.skipBytes((int) raf.length());
                raf.writeBytes(taskTime);
                raf.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            String task = "crontab " + fileName;
            File file = new File("/home/ahmed/Desktop/CronExecuter.sh");
            fos = new FileOutputStream(file);
            fos.write(task.getBytes());
            fos.close();
            Runtime.getRuntime().exec("sudo chmod 775 /home/ahmed/Desktop/CronExecuter.sh");
            Runtime.getRuntime().exec("/bin/sh /home/ahmed/Desktop/CronExecuter.sh");
            LogFile.log("System", "creates Schedule Task for provider " + providername + " and that schedule task will run every " + data.getModifier() + " " + data.getSchedule() + " at " + data.getStartTime() + " starting from " + data.getStartDate());
        } catch (SAXException ex) {
            Logger.getLogger(CustomSchTask.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log("System", "failed to create the schedule task for provider " + providername + " this may be due to : " + ex.getMessage());
        } catch (IOException ex) {
            Logger.getLogger(CustomSchTask.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log("System", "failed to create the schedule task for provider " + providername + " this may be due to : " + ex.getMessage());
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(CustomSchTask.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log("System", "failed to create the schedule task for provider " + providername + " this may be due to : " + ex.getMessage());
        }
    }
}
